package middleware

import (
	"Server/logic"
	"fmt"
	"github.com/gin-gonic/gin"
	"net/http"
)

// token认证中间件（权限控制）
func AuthMiddleware() gin.HandlerFunc {
	return func(ctx *gin.Context) {
		tokenString := ctx.Request.Header.Get("Authorization")
		if tokenString == "" {
			ctx.JSON(http.StatusUnauthorized, gin.H{"code": 401, "msg": "权限不足1"})
			ctx.Abort()
			return
		}

		// 去除"Bearer "前缀
		if len(tokenString) > 7 && tokenString[0:7] == "Bearer " {
			tokenString = tokenString[7:]
		}

		token, claims, err := logic.ParseToken(tokenString)
		fmt.Println(tokenString)
		fmt.Println(token, err)
		if err != nil || !token.Valid {
			ctx.JSON(http.StatusUnauthorized, gin.H{"code": 401, "msg": "权限不足2"})
			ctx.Abort()
			return
		}

		// 验证通过后的操作...
		ctx.Set("user", claims) // 将claims存储到context中
		ctx.Next()
	}
}
